import React, { useState, useEffect } from 'react';
import { Card, Typography, Button, Table, Tag, Alert, Tabs } from 'antd';

// Import chart components
import BubbleChart from '../components/charts/BubbleChart';
import BarChart from '../components/charts/BarChart';
import DonutChart from '../components/charts/DonutChart';
import AreaChart from '../components/charts/AreaChart';
import ScatterChart from '../components/charts/ScatterChart';
import FunnelChart from '../components/charts/FunnelChart';

// Import API service
import { strategyAnalyticsService } from '../lib/strategyAnalyticsApi';

const { Title, Text } = Typography;

const StrategyAnalyticsDashboard: React.FC = () => {
  const [selectedPeriod, setSelectedPeriod] = useState<7 | 30 | 90>(7);
  const [updateTime, setUpdateTime] = useState<string>('');

  // State for data from API
  const [bubbleChartData, setBubbleChartData] = useState<any[]>([]);
  const [topStrategiesData, setTopStrategiesData] = useState<any[]>([]);
  const [usageTrendData, setUsageTrendData] = useState<{ labels: string[]; data: number[] }>({ labels: [], data: [] });
  const [conversionFunnelData, setConversionFunnelData] = useState<any[]>([]);
  const [conversionRateData, setConversionRateData] = useState<any[]>([]);
  const [scatterData, setScatterData] = useState<any[]>([]);
  const [strategyTypeDistribution, setStrategyTypeDistribution] = useState<number[]>([34,
    35,
    127,
    17]);
  const [strategySourceDistribution, setStrategySourceDistribution] = useState<number[]>([]);
  const [strategyUsageBySegment, setStrategyUsageBySegment] = useState<any[]>([]);
  const [alertsData, setAlertsData] = useState<any[]>([]);
  const [strategyTypes, setStrategyTypes] = useState<any[]>([
    { name: "专家解读框架", value: "expert_interpretation" },
    { name: "资产配置策略", value: "asset_allocation" },
    { name: '营销策略', value: 'marketing_strategy' },
    { name: '经营引导策略', value: 'business_guidance' },
  ]);


  useEffect(() => {
    // Set initial update time
    setUpdateTime(new Date().toLocaleString('zh-CN'));

    // Load initial data
    loadAllData();
  }, [selectedPeriod]);

  const loadAllData = async () => {
    try {
      // Load static data
      const [
        bubbleChartResponse,
        topStrategiesResponse,
        strategyTypeResponse,
        sourceDistributionResponse,
        usageBySegmentResponse,
        alertsResponse
      ] = await Promise.all([
        strategyAnalyticsService.coverage.getBubbleChartData(),
        strategyAnalyticsService.usage.getTopStrategies(),
        strategyAnalyticsService.coverage.getStrategyTypeDistribution(),
        strategyAnalyticsService.usage.getSourceDistribution(),
        strategyAnalyticsService.usage.getUsageBySegment(),
        strategyAnalyticsService.alerts.getAlerts()
      ]);

      if (bubbleChartResponse.success) setBubbleChartData(bubbleChartResponse.data);
      if (topStrategiesResponse.success) setTopStrategiesData(topStrategiesResponse.data);
      if (strategyTypeResponse.success) {
        setStrategyTypes(strategyTypeResponse.data.types);
        setStrategyTypeDistribution(strategyTypeResponse.data.distribution);
      } else {
        // 如果API失败，使用默认值确保图表正常显示
        console.warn('Strategy type API failed, using default values');
      }
      if (sourceDistributionResponse.success) setStrategySourceDistribution(sourceDistributionResponse.data.data);
      if (usageBySegmentResponse.success) setStrategyUsageBySegment(usageBySegmentResponse.data);
      if (alertsResponse.success) setAlertsData(alertsResponse.data);

      // Load dynamic data based on period
      updateChartsData(selectedPeriod);
    } catch (error) {
      console.error('Error loading data:', error);
    }
  };

  const updateChartsData = async (period: 7 | 30 | 90) => {
    try {
      const [
        trendResponse,
        funnelResponse,
        conversionResponse,
        scatterResponse
      ] = await Promise.all([
        strategyAnalyticsService.usage.getUsageTrend(period),
        strategyAnalyticsService.conversion.getConversionFunnel(period),
        strategyAnalyticsService.conversion.getConversionRates(period),
        strategyAnalyticsService.conversion.getFrequencyVsConversion(period)
      ]);

      if (trendResponse.success) setUsageTrendData(trendResponse.data);
      if (funnelResponse.success) setConversionFunnelData(funnelResponse.data);
      if (conversionResponse.success) setConversionRateData(conversionResponse.data);
      if (scatterResponse.success) setScatterData(scatterResponse.data);
    } catch (error) {
      console.error('Error updating charts data:', error);
    }
  };

  const handlePeriodChange = (period: 7 | 30 | 90) => {
    setSelectedPeriod(period);
    updateChartsData(period);
  };

  const getAverageValues = (period: 7 | 30 | 90) => {
    return {
      averageX: period === 7 ? 100 : period === 30 ? 500 : 1500,
      averageY: 12
    };
  };

  const { averageX, averageY } = getAverageValues(selectedPeriod);

  // Table columns for strategy usage by segment
  const columns = [
    {
      title: '客群',
      dataIndex: 'segment',
      key: 'segment',
      render: (text: string) => <Text strong>{text}</Text>
    },
    {
      title: '最常触发策略',
      dataIndex: 'topStrategy',
      key: 'topStrategy'
    },
    {
      title: '日均触发',
      dataIndex: 'dailyAverage',
      key: 'dailyAverage',
      render: (value: number) => `${value}次`
    },
    {
      title: '主要场景',
      dataIndex: 'mainScenario',
      key: 'mainScenario',
      render: (text: string) => <Tag color="blue">{text}</Tag>
    }
  ];

  const getAlertType = (type: string) => {
    switch (type) {
      case 'warning':
        return 'warning';
      case 'error':
        return 'error';
      case 'info':
        return 'info';
      default:
        return 'warning';
    }
  };

  // Tab items for the four sections
  const tabItems = [
    {
      key: '1',
      label: '策略覆盖情况',
      children: (
        <div className="p-6 overflow-y-auto" style={{ height: 'calc(100vh - 160px)' }}>
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
            <Card
              className="lg:col-span-3 hover:shadow-lg transition-shadow duration-300"
              title="综合策略覆盖分析 (客群、场景、类型)"
            >
              <BubbleChart data={bubbleChartData} height={500} />
            </Card>
            <Card
              className="lg:col-span-1 hover:shadow-lg transition-shadow duration-300"
              title="策略类型总览"
            >
              <DonutChart
                data={strategyTypeDistribution}
                labels={strategyTypes.map(t => t.name)}
                totalLabel="总策略数"
                height={450}
                colors={['#1d4ed8', '#3b82f6', '#b0b5bf', '#a9d1fe']}
              />
            </Card>
          </div>
        </div>
      ),
    },
    {
      key: '2',
      label: '策略使用情况',
      children: (
        <div className="p-6 overflow-y-auto" style={{ height: 'calc(100vh - 160px)' }}>
          {/* Time Period Filter */}
          <div className="flex justify-end items-center mb-6">
            <div className="flex items-center space-x-2">
              <Button
                type={selectedPeriod === 7 ? 'primary' : 'default'}
                onClick={() => handlePeriodChange(7)}
                size="small"
              >
                近7日
              </Button>
              <Button
                type={selectedPeriod === 30 ? 'primary' : 'default'}
                onClick={() => handlePeriodChange(30)}
                size="small"
              >
                近30日
              </Button>
              <Button
                type={selectedPeriod === 90 ? 'primary' : 'default'}
                onClick={() => handlePeriodChange(90)}
                size="small"
              >
                近90日
              </Button>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <Card
              className="lg:col-span-2 hover:shadow-lg transition-shadow duration-300"
              title="每日策略触发次数趋势"
            >
              <AreaChart
                data={usageTrendData.data}
                categories={usageTrendData.labels}
                title="策略触发次数"
              />
            </Card>
            <Card
              className="hover:shadow-lg transition-shadow duration-300"
              title="Top 10 调用策略"
            >
              <BarChart
                data={topStrategiesData.slice(0, 10).map(s => s.count)}
                categories={topStrategiesData.slice(0, 10).map(s => s.name)}
                horizontal={true}
                color="#818cf8"
              />
            </Card>
            <Card
              className="hover:shadow-lg transition-shadow duration-300"
              title="策略调用来源"
            >
              <DonutChart
                data={strategySourceDistribution}
                labels={['理财师主动调用', '系统自动召回']}
                colors={['#4f46e5', '#a5b4fc']}
                showTotal={false}
              />
            </Card>
            <Card
              className="lg:col-span-4 hover:shadow-lg transition-shadow duration-300"
              title="策略使用频率 × 客群"
            >
              <div className="overflow-x-auto">
                <Table
                  columns={columns}
                  dataSource={strategyUsageBySegment}
                  pagination={false}
                  size="small"
                  rowKey="segment"
                />
              </div>
            </Card>
          </div>
        </div>
      ),
    },
    {
      key: '3',
      label: '转化与效果分析',
      children: (
        <div className="p-6 overflow-y-auto" style={{ height: 'calc(100vh - 160px)' }}>
          {/* Time Period Filter */}
          <div className="flex justify-end items-center mb-6">
            <div className="flex items-center space-x-2">
              <Button
                type={selectedPeriod === 7 ? 'primary' : 'default'}
                onClick={() => handlePeriodChange(7)}
                size="small"
              >
                近7日
              </Button>
              <Button
                type={selectedPeriod === 30 ? 'primary' : 'default'}
                onClick={() => handlePeriodChange(30)}
                size="small"
              >
                近30日
              </Button>
              <Button
                type={selectedPeriod === 90 ? 'primary' : 'default'}
                onClick={() => handlePeriodChange(90)}
                size="small"
              >
                近90日
              </Button>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Card
              className="hover:shadow-lg transition-shadow duration-300"
              title="策略转化漏斗"
            >
              <FunnelChart data={conversionFunnelData} />
            </Card>
            <Card
              className="hover:shadow-lg transition-shadow duration-300"
              title="不同策略类型平均转化率"
            >
              <BarChart
                data={conversionRateData.filter(d => d.type !== '专家解读框架' && d.type !== '资产配置策略').map(d => d.rate)}
                categories={conversionRateData.filter(d => d.type !== '专家解读框架' && d.type !== '资产配置策略').map(d => d.type)}
                distributed={true}
                colors={['#6366f1', '#818cf8']}
              />
            </Card>
            <Card
              className="hover:shadow-lg transition-shadow duration-300"
              title="策略触发频次 vs 成交比率"
            >
              <ScatterChart
                data={scatterData}
                xTitle="触发频次"
                yTitle="成交比率 (%)"
                averageX={averageX}
                averageY={averageY}
              />
            </Card>
          </div>
        </div>
      ),
    },
    {
      key: '4',
      label: '策略运营预警',
      children: (
        <div className="p-6 overflow-y-auto" style={{ height: 'calc(100vh - 160px)' }}>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {alertsData.map((alert, index) => (
              <Alert
                key={index}
                message={alert.title}
                description={alert.description}
                type={getAlertType(alert.type)}
                showIcon
                className="hover:shadow-lg transition-shadow duration-300"
              />
            ))}
          </div>
        </div>
      ),
    },
  ];

  return (
    <div className="flex flex-col bg-gray-50" style={{ height: '100vh' }}>
      {/* Header */}
      <header className="flex flex-col md:flex-row justify-between items-start md:items-center px-4 sm:px-6 md:px-8 py-4 bg-white border-b border-gray-200">
        <div>
          <Title level={3} className="!mb-2 text-gray-800">
            策略运营总览
          </Title>
          <Text className="text-gray-500 text-sm">
            数据更新于: {updateTime}
          </Text>
        </div>
      </header>

      {/* Tabs Container with Scrollable Content */}
      <div className="flex-1 overflow-hidden">
        <Tabs
          defaultActiveKey="1"
          items={tabItems}
          className="analytics-tabs h-full"
          size="large"
        />
      </div>
    </div>
  );
};

export default StrategyAnalyticsDashboard; 